//
//  LeftViewController.m
//  KMedicine
//
//  Created by 曹牧 on 16/7/5.
//  Copyright © 2016年 caomu. All rights reserved.
//

#import "LeftViewController.h"
#import "DoctorApplyController.h"
#import "CaseManageController.h"
#import "FocusDoctorController.h"
#import "SettingViewController.h"
#import "AboutProducController.h"
#import "SharedViewController.h"
#import "LoginViewController.h"
#import "RegisterViewController.h"
#import "UserInfoController.h"


//#########################
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>
//##########################

@interface LeftViewController ()<UITableViewDelegate,UITableViewDataSource>
/** 没有登录界面 */
@property (nonatomic, strong) UIView *noLoginBGView;

/** 有登录界面 */
@property (nonatomic, strong) UIView *loginBGView;

@property (nonatomic,weak) UIView * blankView;

/** tableView */
@property (nonatomic, strong) UITableView *tableview;

@property (nonatomic, strong) NSArray *arrData1;
@property (nonatomic, strong) NSArray *arrData2;

////头像
//@property (nonatomic,weak) UIButton * portrait;
@property (nonatomic,strong) UIImage * portrait;//从偏好中读取到的image 图片


@end

@implementation LeftViewController
static NSString * identifier = @"cell";
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.hidden = YES;//隐藏导航条
    self.arrData1 = @[@"名医通申请",@"病例管理",@"关注医生"];
    self.arrData2 = @[@"设置与帮助",@"关于产品",@"分享给好友"];
    
    [self setupUI];
}

#pragma mark -
#pragma mark - top
- (void)setupUI{
    
    //空view
    UIView * blankView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 120)];
    self.blankView = blankView;
    [self.view addSubview:blankView];
    
    NSNumber * isLogin = [[NSUserDefaults standardUserDefaults] objectForKey:@"isLogin"];
    if (isLogin.intValue) {
        [self.blankView addSubview:self.loginBGView];
        
    }else{
        [self.blankView addSubview:self.noLoginBGView];
    }
    
   
//    [self.blankView addSubview:self.noLoginBGView];
    
    //left pannel 上有两个控件: 1.tableview  2.uiview
    [self.view addSubview:self.tableview];
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.mas_equalTo(0);
        make.top.mas_equalTo(self.blankView.bottom);
        make.width.mas_equalTo([UIScreen mainScreen].bounds.size.width*0.8);
    }];
    
}

#pragma mark -
#pragma mark - tableView dataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section == 0) {
        return self.arrData1.count;
    }else{
        return self.arrData2.count;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    //两种方式:  1.手动创建cell  2.注册类
    if(!cell){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    if(indexPath.section == 0){
        cell.textLabel.text = self.arrData1[indexPath.row];
    }else{
        cell.textLabel.text = self.arrData2[indexPath.row];
    }
    return cell;
    
}

#pragma mark -
#pragma mark - tableView delegate 

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        return 0.0000001;//注意:如果返回0,系统会返回默认的section header 的 height!!
    }
    return 5;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    UIViewController *  vc;
    
    if (section == 0) {
        
        if (![[NSUserDefaults standardUserDefaults] boolForKey:@"isLogin"]) {
            [SVProgressHUD showSuccessWithStatus:@"请先登录"];//显示
            [SVProgressHUD setFadeInAnimationDuration:0];
            [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
            [SVProgressHUD dismissWithDelay:1];
            return;
        }
    }
    
    if (section==0) {
        switch (row) {
            case 0:
                vc = (DoctorApplyController *)[[DoctorApplyController alloc] init];
                break;
            case 1:
                
                vc = (CaseManageController *)[[CaseManageController alloc] init];
                break;
            case 2:
                vc = (FocusDoctorController *)[[FocusDoctorController alloc] init];
                break;
            default:
                break;
        }
        //设置vc title
        vc.title = self.arrData1[row];
        
    }else{
        if (row == 0) {
            
            vc = [[SettingViewController alloc] init];
            //遗留问题:1.强转  2.self.subviews[0]  为空
            ((SettingViewController *)vc).cancelSuccess= ^{
                                    [self.loginBGView removeFromSuperview];
                                    [self.view addSubview:self.noLoginBGView];
                                     };
        }else if(row == 1){
            vc = (AboutProducController *)[[AboutProducController alloc] init];

        }else {
//            vc = (SharedViewController *)[[SharedViewController alloc] init];
            [self shared:[UIImage imageNamed:@"banner"]];
            return;

        }
        vc.title = self.arrData2[row];
    }
    
    //跳转到 centerPanel中对应的控制器(内部:1.显示centerPannel 2.跳转到对应的nav 中的vc)
    [self jumpToOtherViewController:vc];
    
    //取消选中该行
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

}

- (void)shared:(UIImage *)img{
    
    //1、创建分享参数
    NSArray* imageArray = @[img];
    //（注意：图片必须要在Xcode左边目录里面，名称必须要传正确，如果要分享网络图片，可以这样传iamge参数 images:@[@"http://mob.com/Assets/images/logo.png?v=20150320"]）
    if (imageArray) {
        
        NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
        [shareParams SSDKSetupShareParamsByText:@"KMedicine下载地址为:www.itcast.cn"
                                         images:imageArray
                                            url:[NSURL URLWithString:@"www.itcast.cn"]
                                          title:@"分享标题"
                                           type:SSDKContentTypeAuto];
        //2、分享（可以弹出我们的分享菜单和编辑界面）
        [ShareSDK showShareActionSheet:nil //要显示菜单的视图, iPad版中此参数作为弹出菜单的参照视图，只有传这个才可以弹出我们的分享菜单，可以传分享的按钮对象或者自己创建小的view 对象，iPhone可以传nil不会影响
                                 items:nil
                           shareParams:shareParams
                   onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                       
                       switch (state) {
                           case SSDKResponseStateSuccess:
                           {
                               UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功"
                                                                                   message:nil
                                                                                  delegate:nil
                                                                         cancelButtonTitle:@"确定"
                                                                         otherButtonTitles:nil];
                               [alertView show];
                               break;
                           }
                           case SSDKResponseStateFail:
                           {
                               UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                               message:[NSString stringWithFormat:@"%@",error]
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"OK"
                                                                     otherButtonTitles:nil, nil];
                               [alert show];
                               break;
                           }
                           default:
                               break;
                       }
                   }
         ];}
    
}

#pragma mark -
#pragma mark - lazy
- (UITableView *)tableview{
    
    if(!_tableview){
        _tableview = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        //设置代理方法
        _tableview.delegate = self;
        _tableview.dataSource = self;
    }
    return _tableview;
}

- (UIView *)loginBGView{
    
    if (!_loginBGView) {
        
        _loginBGView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 120)];
        _loginBGView.backgroundColor = kThemeColor;

        //1.头像
        
        UIButton * portrait = [[UIButton alloc] init];
        
        [_loginBGView addSubview:portrait];
        
        //读取图片信息
        UIImage * iconImage = [UIImage imageWithContentsOfFile:kFilePath(@"userProtraitPicture.png")];
        
        if (!iconImage) {
            iconImage = [UIImage imageNamed:@"good_image_default"];
        }
        
        [portrait setImage:iconImage forState:UIControlStateNormal];
        self.portrait = iconImage;//赋值
        
        [portrait mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(70, 70));
            make.left.mas_equalTo(20);
            make.top.mas_equalTo(30);
        }];
        [portrait addTarget:self action:@selector(clickProtrait:) forControlEvents:UIControlEventTouchUpInside];
 
        //设置圆角
        portrait.layer.cornerRadius = 35;
        portrait.layer.masksToBounds = YES;

        //2.昵称
        UILabel * nameLabel = [[UILabel alloc] init];
        nameLabel.text = @"王二才";
        nameLabel.font = FONT(16);
        [_loginBGView addSubview:nameLabel];
        [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(portrait).offset(5);
            make.left.mas_equalTo(portrait.mas_right).offset(15);
        }];
        
        //个人资料
        UILabel * perLabel = [[UILabel alloc] init];
        perLabel.text = @"查看个人资料";
        perLabel.font = FONT(16);
        [_loginBGView addSubview:perLabel];
        [perLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(portrait).offset(-5);
            make.left.mas_equalTo(portrait.mas_right).offset(15);
        }];
        //添加手势
        perLabel.userInteractionEnabled = YES;
        UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
        [perLabel addGestureRecognizer:tapGesture];
        
    }
    return _loginBGView;
}

#pragma mark -
#pragma mark - 查看用户label的手势
- (void)tap:(UITapGestureRecognizer *)tap{
    
    UserInfoController * infoController = [[UserInfoController alloc] init];
    [self jumpToOtherViewController:infoController];
}

#pragma mark -
#pragma mark - portrait 的点击事件

- (void)clickProtrait:(UIButton *)button{
    
    UserInfoController * userInfoVc = [[UserInfoController alloc] init];
    
    userInfoVc.protraitImage = self.portrait;//赋值
    
    userInfoVc.returnImage = ^(UIImage * image){
        
        NSArray * array = self.loginBGView.subviews;
        [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            if ([obj isKindOfClass:[UIButton class]]) {
                [obj setImage:image forState:UIControlStateNormal];
            }
            
        }];
    };
    
    [self jumpToOtherViewController:userInfoVc];
}

- (UIView *)noLoginBGView{
    
    if (!_noLoginBGView) {
        
        _noLoginBGView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 120)];
        _noLoginBGView.backgroundColor = kThemeColor;
        
        //头像
        UIImageView * iconView = [[UIImageView alloc] init];
        iconView.image = [UIImage imageNamed:@"name"];
        [_noLoginBGView addSubview:iconView];
        iconView.bounds = CGRectMake(0, 0, 45, 45);
        iconView.center = CGPointMake(self.view.frame.size.width / 2.0f, 50);

 
        //登录
        UIButton * loginBtn = [[UIButton alloc] init];
        loginBtn.tag = 1;
        [loginBtn setTitle:@"登录" forState:UIControlStateNormal];
        [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_noLoginBGView addSubview:loginBtn];
        [loginBtn addTarget:self action:@selector(didClickBtn:) forControlEvents:UIControlEventTouchUpInside];
        [loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(iconView.mas_centerX).offset(-10);
            make.size.mas_equalTo(CGSizeMake(100, 30));
            make.top.mas_equalTo(iconView.mas_bottom).offset(10);
        }];
  
        //注册
        UIButton * registerBtn = [[UIButton alloc] init];
        registerBtn.tag = 2;
        [_noLoginBGView addSubview:registerBtn];
        [registerBtn setTitle:@"注册" forState:UIControlStateNormal];
        [registerBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [registerBtn addTarget:self action:@selector(didClickBtn:) forControlEvents:UIControlEventTouchUpInside];
        [registerBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(100, 30));
            make.left.mas_equalTo(iconView.mas_centerX).offset(10);
            make.top.mas_equalTo(iconView.mas_bottom).offset(10);
        }];

    }
    return _noLoginBGView;
}

- (void)didClickBtn:(UIButton *)sender{
    
    if (sender.tag == 1) {//login
        
        LoginViewController * loginVc = [[LoginViewController alloc] init];

        loginVc.loginSuccess = ^{
            
            [self.noLoginBGView removeFromSuperview];
            [self.view addSubview:self.loginBGView];
        };

        [self jumpToOtherViewController:loginVc];
        
    }else{//register
        
        RegisterViewController * registVc = [[RegisterViewController alloc] init];
        [self jumpToOtherViewController:registVc];
        
    }
}


@end
